<template>
    <div class="addresses-content">
        <el-button type="primary" @click="showAddDialog = true" class="add-btn">
            新增地址
        </el-button>
        <el-table :data="localAddresses" style="width: 100%" border>
            <el-table-column prop="receiverName" label="收货人" width="120" />
            <el-table-column prop="receiverPhone" label="手机号" width="120" />
            <el-table-column prop="province" label="省份" width="100" />
            <el-table-column prop="city" label="城市" width="100" />
            <el-table-column prop="district" label="区域" width="100" />
            <el-table-column prop="detailAddress" label="详细地址" />
            <el-table-column prop="isDefault" label="默认地址" width="100">
                <template #default="scope">
                    <el-tag v-if="scope.row.isDefault" type="success">是</el-tag>
                    <el-tag v-else type="info">否</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button size="small" @click="edit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteAddress(scope.row.id)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增/编辑地址对话框 -->
        <el-dialog v-model="showAddDialog" :title="isEdit ? '编辑地址' : '新增地址'" width="45%" class="modern-dialog">
            <el-form :model="addressForm" label-width="80px" class="modern-form">
                <el-form-item label="收货人" class="modern-form-item">
                    <el-input v-model="addressForm.receiverName" class="modern-input" />
                </el-form-item>
                <el-form-item label="手机号" class="modern-form-item">
                    <el-input v-model="addressForm.receiverPhone" class="modern-input" />
                </el-form-item>
                <el-form-item label="地区" class="modern-form-cascader">
                    <el-cascader 
                        v-model="selectedRegion" 
                        :options="regionOptions" 
                        :props="cascaderProps" 
                        @change="handleRegionChange" 
                        style="width: 100%"
                        class="modern-cascader" />
                </el-form-item>
                <el-form-item label="详细地址" class="modern-form-item">
                    <el-input v-model="addressForm.detailAddress" type="textarea" class="modern-textarea" />
                </el-form-item>
                <el-form-item label="默认地址" class="modern-form-item">
                    <el-switch v-model="addressForm.isDefault" class="modern-switch" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer modern-footer">
                    <el-button @click="showAddDialog = false" class="modern-button">取消</el-button>
                    <el-button type="primary" @click="saveAddress" class="modern-button">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UserAddressType } from '@/type/user'
import {
    getProvinces,
    getCities,
    getdistricts
} from '@/api/profile'

const props = defineProps<{
    addresses: any[]
}>()

const emit = defineEmits<{
    (e: 'fetch-addresses'): void
    (e: 'edit', address: any): void
    (e: 'delete', id: number): void
    (e: 'save', addressData: UserAddressType, isEdit: boolean): void
}>()

const localAddresses = ref<any[]>([])
const showAddDialog = ref(false)
const isEdit = ref(false)
// 创建一个新的地址表单对象用于新增
const newAddressForm = ref<UserAddressType>({
    id: 0,
    receiverName: '',
    receiverPhone: '',
    province: '',
    city: '',
    district: '',
    detailAddress: '',
    isDefault: false
})
// 创建一个编辑用的地址表单对象
const editAddressForm = ref<UserAddressType>({
    id: 0,
    receiverName: '',
    receiverPhone: '',
    province: '',
    city: '',
    district: '',
    detailAddress: '',
    isDefault: false
})
// 当前正在使用的表单对象
const addressForm = ref<UserAddressType>(newAddressForm.value)
const selectedRegion = ref<number[]>([])
const regionOptions = ref<Array<{
  id: number;
  name: string;
  children: any[];
}>>([])

// 监听地址数据变化
watch(() => props.addresses, (newAddresses) => {
    localAddresses.value = Array.isArray(newAddresses) ? [...newAddresses] : []
}, { immediate: true })

const cascaderProps = {
    value: 'id',
    label: 'name',
    children: 'children',
    lazy: true,
    lazyLoad: async (node: any, resolve: any) => {
        const { level, value } = node;
        let nodes = [];

        try {
            if (level === 0) {
                // 加载省份
                const res = await getProvinces();
                nodes = res.data.data.map((item: any) => ({
                    id: item.id,
                    name: item.name,
                    children: [] // 初始化 children 为空数组
                }));
            } else if (level === 1) {
                // 加载城市
                const res = await getCities(value);
                nodes = res.data.data.map((item: any) => ({
                    id: item.id,
                    name: item.name,
                    children: [] // 初始化 children 为空数组
                }));
            } else if (level === 2) {
                // 加载区县
                const res = await getdistricts(value);
                nodes = res.data.data.map((item: any) => ({
                    id: item.id,
                    name: item.name,
                    leaf: true // 区县级别设置为叶子节点
                }));
            }
        } catch (error) {
            ElMessage.error('地区数据加载失败');
            console.error(error); // 打印错误信息，便于调试
        }

        resolve(nodes);
    }
}

// 处理地区选择变化
const handleRegionChange = (value: number[]) => {
    if (!value || value.length !== 3) {
        // 重置地址表单中的省市区
        addressForm.value.province = '';
        addressForm.value.city = '';
        addressForm.value.district = '';
        return;
    }

    // 获取选中的省市区名称
    let provinceName = '';
    let cityName = '';
    let districtName = '';

    const findNameById = (options: any[], id: number): string => {
        const item = options.find((opt) => opt.id === id);
        return item ? item.name : '';
    };

    // 省份名称
    provinceName = findNameById(regionOptions.value, value[0]);

    // 城市名称
    const cityOptions = regionOptions.value.find((opt:any) => opt.id === value[0])?.children || [];
    cityName = findNameById(cityOptions, value[1]);

    // 区县名称
    const districtOptions = cityOptions.find((opt:any) => opt.id === value[1])?.children || [];
    districtName = findNameById(districtOptions, value[2]);

    // 更新地址表单中的省市区名称
    addressForm.value.province = provinceName;
    addressForm.value.city = cityName;
    addressForm.value.district = districtName;
};

const edit = (address: any) => {
    isEdit.value = true;
    // 使用编辑专用的表单对象，避免修改原始数据
    editAddressForm.value = {
        id: address.id || 0,
        receiverName: address.receiverName || '',
        receiverPhone: address.receiverPhone || '',
        province: address.province || '',
        city: address.city || '',
        district: address.district || '',
        detailAddress: address.detailAddress || '',
        isDefault: address.isDefault || false
    };
    
    addressForm.value = editAddressForm.value;

    // 根据 province、city 和 district 的名称找到对应的 ID 并设置 selectedRegion
    const findIdByName = (options: any[], name: string): number | undefined => {
        return options.find((opt) => opt.name === name)?.id;
    };

    const provinceId = findIdByName(regionOptions.value, editAddressForm.value.province);
    const cityId = provinceId ? findIdByName(regionOptions.value.find((opt: any) => opt.id === provinceId)?.children || [], editAddressForm.value.city) : undefined;
    const districtId = cityId ? findIdByName(regionOptions.value.find((opt: any) => opt.id === provinceId)?.children?.find((opt:any) => opt.id === cityId)?.children || [], editAddressForm.value.district) : undefined;

    if (provinceId && cityId && districtId) {
        selectedRegion.value = [provinceId, cityId, districtId];
    }

    showAddDialog.value = true;
};

const deleteAddress = (id: number) => {
    emit('delete', id)
}

const saveAddress = () => {
    // 如果选择了地区，此时 addressForm 中的 province、city 和 district 已经是名称
    emit('save', addressForm.value, isEdit.value);
    showAddDialog.value = false;
    resetForm();
};

const resetForm = () => {
    // 重置为新增表单对象
    newAddressForm.value = {
        id: 0,
        receiverName: '',
        receiverPhone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        isDefault: false
    }
    addressForm.value = newAddressForm.value;
    selectedRegion.value = []
    isEdit.value = false
}

// 初始化获取地址列表
onMounted(async () => {
    try {
        const res = await getProvinces();
        regionOptions.value = res.data.data.map((item: any) => ({
            id: item.id,
            name: item.name,
            children: [] // 初始化 children 为空数组
        }));
    } catch (error) {
        ElMessage.error('初始地区数据加载失败');
        console.error(error); // 打印错误信息，便于调试
    }
});
</script>

<style scoped>
.addresses-content {
    max-width: 1000px;
    margin-left: 10px;
}

.add-btn {
    margin-bottom: 20px;
}

.modern-dialog {
    /* 对话框整体样式 */
    border-radius: 12px; /* 圆角边框 */
}

.modern-form {
    /* 表单整体样式 */
    padding: 24px; /* 增加内边距 */
}

.modern-form-item {
    /* 表单项样式 */
    margin-bottom: 24px; /* 增加表单项间距 */
}
.modern-form-cascader{
    margin-bottom: 24px;
    width: 60%;
}

.modern-input, .modern-cascader, .modern-textarea {
    /* 输入框、级联选择器、文本域样式 */
    border-radius: 8px; /* 圆角边框 */
    width: 80%;
}

.modern-textarea {
    height: 100px; /* 增加文本域高度 */
}

.modern-switch {
    /* 开关样式 */
    margin-left: 16px; /* 调整开关与标签的间距 */
}

.modern-footer {
    /* 底部按钮区域样式 */
    text-align: right; /* 右对齐 */
    padding: 16px; /* 调整内边距 */
}

.modern-button {
    /* 按钮样式 */
    border-radius: 8px; /* 圆角边框 */
    margin-left: 8px; /* 按钮间距 */
}
</style>